Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
¿Cómo resolver las actualizaciones de estado dependiente "a la manera de reaccionar"?

Me topé con una pregunta muy interesante y me gustaría saber cómo resolverla mejor en React. Asuma el siguiente código:

 const [qrText, setQrText] = useState("") ... const generateQrCode = () => { // set other state inside the "then" QRCode.toDataUrl(qrText).then(...) } const handleChange = (e) => { setQrText(e.target.value) generateQrCode() }

Este código no es seguro, ya que las actualizaciones de estado se realizan de forma asincrónica y, cuando se ejecuta generateQrCode , qrText aún podría tener el valor anterior.

Siempre tendí a resolver este problema usando un useEffect con una matriz de dependencia:

 const [qrText, setQrText] = useState("") ... const handleChange = (e) => { setQrText(e.target.value) } useEffect(() => { const generateQrCode = () => { // set other state inside the "then" QRCode.toDataUrl(qrText).then(...) } generateQrCode() }, [qrText])

Sin embargo, recientemente vi un video de YouTube de una conferencia de React , donde un ingeniero senior dijo que se supone que useEffect solo se use para sincronizar datos con servicios externos o el DOM. En cambio, las personas deben actualizar el estado solo en los controladores de eventos .

Entonces, ¿es esta la forma correcta de manejar este escenario?

 const [qrText, setQrText] = useState("") ... // this now takes the qrText as argument const generateQrCode = (qrTextArg) => { // set other state inside the "then" QRCode.toDataUrl(qrTextArg).then(...) } const handleChange = (e) => { const value = e.target.value setQrText(value) generateQrCode(value) // pass the event value, instead of relying on the "qrText" state }

Esto equivaldría al enfoque "basado en eventos", pero se siente un poco imperativo y no "reaccionar".

Así que me pregunto, ¿cuál es la forma prevista de hacer esto?

¡Gracias por tus respuestas!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!